import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Layout.vue'),
      meta: { requiresAuth: true },
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/Dashboard.vue'),
          meta: { requiresAuth: true }
        },
        // 学生路由
        {
          path: 'courses',
          name: 'courseList',
          component: () => import('../views/student/CourseListView.vue'),
          meta: { requiresAuth: true, roles: ['student', 'teacher', 'admin'] }
        },
        {
          path: 'my-courses',
          name: 'myCourses',
          component: () => import('../views/student/MyCoursesView.vue'),
          meta: { requiresAuth: true, roles: ['student'] }
        },
        // 教师路由
        {
          path: 'teacher/courses',
          name: 'teacherCourses',
          component: () => import('../views/teacher/TeacherCoursesView.vue'),
          meta: { requiresAuth: true, roles: ['teacher'] }
        },
        // 管理员路由
        {
          path: 'admin/users',
          name: 'adminUsers',
          component: () => import('../views/admin/UserManagementView.vue'),
          meta: { requiresAuth: true, roles: ['admin'] }
        },
        {
          path: 'admin/courses',
          name: 'adminCourses',
          component: () => import('../views/admin/CourseManagementView.vue'),
          meta: { requiresAuth: true, roles: ['admin'] }
        },
        {
          path: 'admin/selections',
          name: 'adminSelections',
          component: () => import('../views/admin/SelectionManagementView.vue'),
          meta: { requiresAuth: true, roles: ['admin'] }
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/auth/LoginView.vue')
    },
    {
      path: '/403',
      name: 'forbidden',
      component: () => import('../views/errors/ForbiddenView.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('../views/errors/NotFoundView.vue')
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  // 注意：store已经在main.js中初始化，不需要在每次路由跳转时重复初始化

  if (to.meta.requiresAuth) { // 如果路由需要认证
    if (authStore.isLoggedIn) { // 检查是否已登录
      if (to.meta.roles && to.meta.roles.length > 0) { // 如果有角色限制
        if (authStore.user && to.meta.roles.includes(authStore.user.role)) {
          next() // 用户角色符合，放行
        } else {
          next('/403') // 无权限，跳转到 403 页面
        }
      } else {
        next() // 无角色限制，已登录即放行
      }
    } else {
      // 未登录，跳转到登录页，并带上当前路由路径作为查询参数，登录成功后可跳回
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 如果路由不需要认证 (例如登录页)
    if (to.name === 'login' && authStore.isLoggedIn) {
      // 如果已登录还想去登录页，则跳转到首页
      next({ name: 'home' })
    } else {
      next() // 放行
    }
  }
})

export default router
